package com.zwd.deep.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.List;

/**
 * 跨域配置
 * @author zwd
 */
@Configuration
public class CorsConfig {
    /*@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有接口
                .allowedOrigins("http://192.168.218.204:3000","http://192.168.218.87:3000","http://localhost:3000") // 允许跨域的域名，可以用*表示允许任何域名使用
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许任何方法（post、get等）
                .allowedHeaders("*","token") // 允许所有头，并且特别允许token头
                .exposedHeaders("token") // 暴露token头给前端
                .allowCredentials(true); // 带上cookie信息
    }*/

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        // 添加多个允许的源，使用List来存储多个源
        List<String> allowedOrigins = Arrays.asList(
                "http://192.168.141.204:5173",
                "http://192.168.218.87:3000",
                "http://localhost:5173",
                "http://localhost:5174"
        );
        config.setAllowedOrigins(allowedOrigins);
        config.addAllowedHeader("*");
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
